import config
from views.BaseView import BaseView
from eventlet.wsgi import Input
from utils import status_code
import jwt, json
from database.db import session, User
from utils.jsonify import jsonify
from collections import defaultdict


class LoginView(BaseView):

    def POST(self, env, start_response):
        '''
        data 格式 {
            "username":"用户名",
            "password": "密码",
            "force": '是否强制登陆，  如果用户登录了 会把正在连接的socket断开连接'
        }
        如果嫌表单验证太麻烦  请在项目中集成WTForms  我在这里不做表单验证  你们一定要做


        '''
        data = json.loads(env['wsgi.input'].read())
        user = session.query(User).filter(User.username == data['username']).first()
        if user and user.password == data['password']:
            token = jwt.encode({
                'userid': user.id,
                'username': user.username
            }, key=config.TOKEN_KEY)
            res = {
                'code': 200,
                'msg': '登录成功',
                'data': {
                    "token": token.decode('utf-8')
                }
            }
            return jsonify(res, start_response)
        return jsonify({
            'code': 400,
            'msg': '用户名密码错误'
        }, start_response)
